package com.sc.thread.bingfabiancheng;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * Created by Shen Chao on 2018-06-12-012.
 * <p>
 * 线程的重用
 */
public class CyclicBarrierTest3 {
    public static void main(String[] args) {
        int N = 4;
        CyclicBarrier cyclicBarrier = new CyclicBarrier(N, () ->
                System.out.println("当前线程：" + Thread.currentThread().getName())
        );

        for (int i = 0; i < N; i++) {
            new Writer(cyclicBarrier).start();
        }

        try {
            Thread.sleep(25000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("CyclicBarrier重用");

        for (int i = 0; i < N; i++) {
            new Writer(cyclicBarrier).start();
        }
    }

    static class Writer extends Thread {
        private CyclicBarrier cyclicBarrier;

        private Writer(CyclicBarrier cyclicBarrier) {
            this.cyclicBarrier = cyclicBarrier;
        }

        @Override
        public void run() {
            try {
                System.out.println("线程： " + Thread.currentThread().getName() + "正在写数据");
                //模拟写数据
                Thread.sleep(5000);
                System.out.println("线程： " + Thread.currentThread().getName() + "写入数据完毕，等待其他线程");
                cyclicBarrier.await(2000, TimeUnit.MILLISECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                e.printStackTrace();
            }
            System.out.println("所有线程执行完毕，继续执行");
        }
    }
}
